// CartPage.js
import strHtml from "./CartPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { productService } from "../../services/productService";

export class CartPage {
  constructor() {
    this.dom = null;
    this.cart = [];
    this.productList = [];
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);
    await this._loadData();
    this._renderCartTable();
    this._bindEvents();
    return this.dom;
  }

  async _loadData() {
    try {
      // 从后端获取最新商品数据
      const response = await productService.getAll();
      this.productList = response;

      // 从本地存储获取购物车数据
      this.cart = JSON.parse(localStorage.getItem("cart") || "[]");

      // 验证购物车中的商品
      await this._validateCartItems();
    } catch (error) {
      console.error("加载购物车数据失败:", error);
      this.productList = [];
      this.cart = [];
    }
  }

  async _validateCartItems() {
    let changed = false;
    const validCart = [];

    for (const item of this.cart) {
      const product = this.productList.find(
        (p) => p.productId === item.productId
      );

      if (!product || product.status !== "上架") {
        changed = true;
        continue;
      }

      // 检查库存
      if (product.stock < item.quantity) {
        changed = true;
        item.quantity = product.stock;
        if (product.stock === 0) {
          continue;
        }
      }

      // 更新商品信息
      validCart.push({
        ...item,
        productName: product.productName,
        productImageUrl: product.productImageUrl,
        productPrice: product.productPrice,
        stock: product.stock,
      });
    }

    if (changed) {
      this.cart = validCart;
      this._saveCart();
      if (this.cart.length !== validCart.length) {
        alert("购物车中有商品已下架或库存不足，已自动更新！");
      }
    }
  }

  _bindEvents() {
    // 结算按钮事件
    const checkoutBtn = this.dom.querySelector(".btn-success");
    if (checkoutBtn) {
      checkoutBtn.addEventListener("click", () => {
        if (this.cart.length === 0) {
          alert("购物车为空！");
          return;
        }
        location.hash = "#/check-out";
      });
    }

    // 继续购物按钮事件
    const continueShoppingBtn = this.dom.querySelector(
      ".btn-outline-secondary"
    );
    if (continueShoppingBtn) {
      continueShoppingBtn.addEventListener("click", () => {
        location.hash = "#/market";
      });
    }
  }

  _renderCartTable() {
    const tbody = this.dom.querySelector("#cart-table-body");
    const totalPriceEl = this.dom.querySelector("#cart-total-price");
    const checkoutBtn = this.dom.querySelector(".btn-success");

    if (!tbody || !totalPriceEl) return;

    tbody.innerHTML = "";
    let total = 0;

    if (this.cart.length === 0) {
      tbody.innerHTML = `
        <tr>
          <td colspan="6" class="text-center py-4">
            <p class="text-muted mb-0">购物车是空的，去<a href="#/market" class="text-primary">商城</a>看看吧~</p>
          </td>
        </tr>
      `;
      if (checkoutBtn) checkoutBtn.disabled = true;
      totalPriceEl.innerText = "￥0.00";
      return;
    }

    if (checkoutBtn) checkoutBtn.disabled = false;

    this.cart.forEach((item, index) => {
      const subtotal = item.productPrice * item.quantity;
      total += subtotal;

      const row = document.createElement("tr");
      row.innerHTML = `
        <td>
          <img src="${item.productImageUrl || ""}" alt="${item.productName}" 
               style="width:60px; height:60px; object-fit:cover;">
        </td>
        <td>${item.productName}</td>
        <td>￥${item.productPrice.toFixed(2)}</td>
        <td>
          <div class="input-group input-group-sm" style="width: 120px; margin: 0 auto;">
            <button class="btn btn-outline-secondary btn-quantity" data-action="decrease" data-index="${index}">-</button>
            <input type="number" class="form-control text-center" 
                   min="1" max="${item.stock}" value="${item.quantity}" 
                   data-index="${index}">
            <button class="btn btn-outline-secondary btn-quantity" data-action="increase" data-index="${index}">+</button>
          </div>
        </td>
        <td>
          <button class="btn btn-sm btn-danger btn-delete" data-index="${index}">
            <i class="fa fa-trash"></i>
          </button>
        </td>
        <td>￥${subtotal.toFixed(2)}</td>
      `;

      // 数量调整按钮事件
      row.querySelectorAll(".btn-quantity").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          const action = e.target.dataset.action;
          const input = row.querySelector("input");
          let newQuantity = parseInt(input.value);

          if (action === "increase" && newQuantity < item.stock) {
            newQuantity++;
          } else if (action === "decrease" && newQuantity > 1) {
            newQuantity--;
          }

          input.value = newQuantity;
          this._updateItemQuantity(index, newQuantity);
        });
      });

      // 数量输入框事件
      const quantityInput = row.querySelector("input");
      quantityInput.addEventListener("change", (e) => {
        const newQuantity = parseInt(e.target.value);
        this._updateItemQuantity(index, newQuantity);
      });

      // 删除按钮事件
      const deleteBtn = row.querySelector(".btn-delete");
      deleteBtn.addEventListener("click", () => {
        if (confirm("确定要删除这个商品吗？")) {
          this._removeItem(index);
        }
      });

      tbody.appendChild(row);
    });

    totalPriceEl.innerText = `￥${total.toFixed(2)}`;
  }

  _updateItemQuantity(index, newQuantity) {
    if (newQuantity < 1) {
      newQuantity = 1;
    } else if (newQuantity > this.cart[index].stock) {
      newQuantity = this.cart[index].stock;
      alert("超出库存上限！");
    }

    this.cart[index].quantity = newQuantity;
    this._saveCart();
    this._renderCartTable();
  }

  _removeItem(index) {
    this.cart.splice(index, 1);
    this._saveCart();
    this._renderCartTable();
  }

  _saveCart() {
    localStorage.setItem("cart", JSON.stringify(this.cart));
  }
}
